package org.springframework.session.web.http;

import java.util.Collections;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class HeaderHttpSessionIdResolver implements HttpSessionIdResolver {

	private static final String HEADER_X_AUTH_TOKEN = "X-Auth-Token";

	private static final String HEADER_AUTHENTICATION_INFO = "Authentication-Info";

	private final String headerName;

	public static HeaderHttpSessionIdResolver xAuthToken() {
		return new HeaderHttpSessionIdResolver(HEADER_X_AUTH_TOKEN);
	}

	public static HeaderHttpSessionIdResolver authenticationInfo() {
		return new HeaderHttpSessionIdResolver(HEADER_AUTHENTICATION_INFO);
	}

	public HeaderHttpSessionIdResolver(String headerName) {
		if (headerName == null) {
			throw new IllegalArgumentException("headerName cannot be null");
		}
		this.headerName = headerName;
	}

	@Override
	public List<String> resolveSessionIds(HttpServletRequest request) {
		String headerValue = request.getHeader(this.headerName);
		return (headerValue != null) ? Collections.singletonList(headerValue) : Collections.emptyList();
	}

	@Override
	public void setSessionId(HttpServletRequest request, HttpServletResponse response, String sessionId) {
		response.setHeader(this.headerName, sessionId);
	}

	@Override
	public void expireSession(HttpServletRequest request, HttpServletResponse response) {
		response.setHeader(this.headerName, "");
	}
}
